package xiaoze.veriface.utils;

import java.io.IOException;
import java.util.*;

import sun.misc.BASE64Decoder;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import xiaoze.veriface.constant.PropertiesConstant;
import xiaoze.veriface.http.HttpRequest;
import xiaoze.veriface.http.Key;
import xiaoze.veriface.http.Response;

/**
 * FaceUtils
 * @author xiaoze
 * @date 2018/1/26
 */
public class FaceUtils {

    /**
     * 人脸对比方法，token1和token2是两个不同的Face++的token值
     * @param token1
     * @param token2
     * @return
     */
    public Response compare(String token1, String token2) {

        List<BasicNameValuePair> formparams = new ArrayList<>();
        //涉及到face++技术,请你使用你自己的api_key
        formparams.add(new BasicNameValuePair(Key.KEY_FOR_APIKEY, PropertiesConstant.API_KEY));
        //涉及到face++技术,请你使用你自己的api_secret
        formparams.add(new BasicNameValuePair(Key.KEY_FOR_APISECRET, PropertiesConstant.API_SECRET));
        formparams.add(new BasicNameValuePair(Key.KEY_FOR_FACE_TOKEN1, token1));
        formparams.add(new BasicNameValuePair(Key.KEY_FOR_FACE_TOKEN2, token2));
        return postHttp(formparams, PropertiesConstant.COMPARE_URL);
    }

    /**
     * Post传输
     * @param formparams
     * @param url
     * @return Response
     */
    private static Response postHttp(List<BasicNameValuePair> formparams, String url) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        Response response1 = new Response();
        UrlEncodedFormEntity uefEntity;
        String returnStr = "";
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    returnStr = EntityUtils.toString(entity, "UTF-8");
                    response1.setContent(returnStr.getBytes());
                    response1.setStatus(response.getStatusLine().getStatusCode());
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + returnStr);
                    System.out.println("--------------------------------------");
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response1;

    }

    /**
     * 人脸检测使用到的通用方法封装
     * @param buff
     * @return String
     */
    public Response check(byte[] buff) {

        HashMap<String, String> map = new HashMap<>(16);
        HashMap<String, byte[]> byteMap = new HashMap<>(16);
        //涉及到face++技术,请你使用你自己的api_key
        map.put(Key.KEY_FOR_APIKEY, PropertiesConstant.API_KEY);
        //涉及到face++技术,请你使用你自己的api_secret
        map.put(Key.KEY_FOR_APISECRET, PropertiesConstant.API_SECRET);
        map.put(Key.KEY_FOR_RETURN_LANDMARK, PropertiesConstant.LANDMARK_NUM);
        map.put(Key.KEY_FOR_RETURN_ATTRIBUTES, PropertiesConstant.ATTRIBUTES_NUM);
        byteMap.put(PropertiesConstant.IMAGE_FILE, buff);
        try{
            Response response = HttpRequest.post(PropertiesConstant.DETECT_URL, map, byteMap);
            System.out.println("状态码：" + response.getStatus());
            return response;

        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将前台传回的info = canvas.toDataURL("image/png")，也就是String转为base64String
     */
    public static String getBase64String(String imgString) {
        return imgString.substring(imgString.indexOf(",")+1);
    }

    /**
     * Base64字符串转 二进制流
     *
     * @param base64String Base64
     * @return base64String
     * @throws IOException 异常
     */
    public static byte[] getStringImage(String base64String) throws IOException {
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        return base64String != null ? decoder.decodeBuffer(base64String) : null;
    }

    /**
     * 人脸检测的循环执行次数，防止调用Api时网络使用阻塞
     * @param buff 图片文件
     * @return
     */
    public Response getCheckResponse(byte[] buff){

        int j = 10;
        int i = 0 ;
        for(;i < j;i++){
            Response response = check(buff);
            if((response != null) && (response.getStatus() == 200)){
                System.out.println(new String(response.getContent()));
                return response;
            }
        }
        return null;
    }

    /**
     * 人脸对比的循环执行次数，防止调用Api时网络使用阻塞
     * @param token1
     * @param token2
     * @return
     */
    public Response getCompareResponse(String token1,String token2){

        int j = 10;
        int i = 0 ;
        for(;i < j;i++){
            Response response = compare(token1,token2);
            if((response != null) && (response.getStatus() == 200)){
                return response;
            }
        }
        return null;
    }


}

